﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;

namespace HealthMonitor.Extensions
{
    public static class Guard
    {
        public static MemberExpression AsMemberOrThrow(this Expression expression)
        {
            return expression.ReduceLambda().AsOrThrow<MemberExpression>(); //String.Format(StaticReflection.ErrorFormat, "member"),"expression");
        }

        public static void ThrowIfNull(Expression<Func<object>> expression)
        {
            var body = expression.AsMemberOrThrow();
            var compiled = expression.Compile();
            var value = compiled();
            if (value == null)
                throw new ArgumentNullException(body.Member.Name);
        }
        public static void Assert(bool condition)
        {
            if (condition)
                return;

#if DEBUG
            System.Diagnostics.Debug.Fail("Assertion failed");
#endif

        }
        public static void Assert(Expression<Func<object>> expression, bool condition)
        {
            if (condition)
                return;
            var body = expression.AsMemberOrThrow();
            var name = body.Member.Name;
            throw new ArgumentException(name);
        }

        public static void ThrowIfNullOrEmpty(Expression<Func<String>> expression)
        {
            var body = expression.AsMemberOrThrow();
            var compiled = expression.Compile();
            var value = compiled();
            if (String.IsNullOrEmpty(value))
            {
                throw new ArgumentException(
                        "String is null or empty", body.Member.Name);
            }
        }

    }
}